import { createAxios } from './axios'
import { Modal, message } from 'ant-design-vue'
import { h } from 'vue'
// import { CreateInstanceOptions } from 'tn-axios/lib/types'
import { storage } from '@/utils/Storage'
import { PageEnum } from '@/enums/router'
import { useUserStoreWidthOut } from '@/store/modules/user'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '@/store/mutation-types'
import { useGlobSetting } from '@/hooks/setting'
import { useRouter } from 'vue-router'

const router = useRouter()

// 弱提示
const messageFn = {
  // 错误弹框提示
  error(msg: string) {
    message.error(msg)
  },
  // 成功弹框提示
  success(msg: string) {
    message.success(msg)
  }
}

// 强提示
const modalFn = {
  // 错误弹框提示
  error(msg: string) {
    Modal.error({
      title: 'error',
      content: h('div', {}, [h('p', msg)])
    })
  },
  // 成功弹框提示
  success(msg: string) {
    Modal.success({
      title: 'success',
      content: h('div', {}, [h('p', msg)])
    })
  }
}

// 登陆过期之后的处理方式
function loginTimeoutFn(): string {
  if (router.currentRoute.value?.name === PageEnum.BASE_LOGIN_NAME) {
    return ''
  }
  // 到登录页
  Modal.warning({
    title: '提示',
    content: h('div', {}, [h('p', '登录身份已失效，请重新登录!')]),
    onOk: () => {
      storage.clear()
      router.push({
        path: PageEnum.BASE_LOGIN,
        replace: true
      })
    }
  })
  return '登录超时，请重新登录!'
}
// 获取token的方式
function getTokenFn() {
  return storage.get(ACCESS_TOKEN)
}

// 刷新token的请求
export async function refreshTokenFn() {
  const userStore = useUserStoreWidthOut()
  const refreshToken = storage.get(REFRESH_TOKEN)
  // 如果刷新token也过期了，返回登录页
  if (refreshToken === '-1') {
    storage.clear()
    router.push({
      path: PageEnum.BASE_LOGIN,
      replace: true
    })
  } else {
    const { data } = await userStore.login({ grant_type: 'refresh_token', refresh_token: refreshToken })
    const token = data.access_token
    // alert(token)
    if (token && typeof token === 'string') {
      return token
    }
    storage.clear()
    router.push({
      path: PageEnum.BASE_LOGIN,
      replace: true
    })
  }
}

// globSetting 环境配置文件内容
const globSetting = useGlobSetting()

const axiosInstanceOptions: any = {
  messageFn,
  apiUrl: globSetting.apiUrl,
  modalFn,
  loginApiUrl: '/uaa/oauth/token',
  loginTimeoutFn,
  getTokenFn,
  refreshTokenFn
}

export const http = createAxios(axiosInstanceOptions)
